
import shouquan from '../../../class/login.js'

var WxParse = require('../../../wxParse/wxParse.js');
import tips from '../../../class/Utils/Tips'
import http from '../../../service/http.js'


Page({
  data: {
    currentTab: 0,
    evt: 1,
    animationData: "",
    showModalStatus: false,
    animationDatab: "",
    showModalStatusa: false,
    circular: true,
    indicatorDots: true,
    vertical: false,
    autoplay: true,
    interval: 2000,
    duration: 200,
    isChecked: false,
    buynum: 1,
    minusStatus: 'disabled',
    defaultguige: '',
    collect: false,
    buy_status: "lj_cart",
    addcar_status: "addcart"
  },//规格循环 end
  onLoad: function (options) {
    // 页面加载完成
    showView: (options.showView == "true" ? true : false)

    var that = this;
    that.setData({
      getid: options.id
    })
    wx.getSystemInfo({
      success: function (res) {
        var pageWidth = res.windowWidth;
        var pjvieww = pageWidth
        that.setData({
          scrollHeight: res.windowHeight - 70,
          nbannerimg: pjvieww
        });
      }
    });


    //  测试账号是我，上传后加上appid再改
    var me = { openid: "oUAHy5EC8pMF7ZDiFMcMWMqsUmFM", wx_name: "呵呵", wx_img: "https://wx.qlogo.cn/mmopen/vi_32/Q0j4TwGTfTIqjzlA7EFocFjPrkdM7IAoqcNTIPLIS1mvVxG0BXCMWL483Hx1OoCuoA4ia9nXY7ye24esvhsF05g/132", userid: "1" }
    wx.setStorageSync('user', me);

    var myinfo = { "nickName": " 策 ", "gender": 1, "language": "zh_CN", "city": "Shenyang", "province": "Liaoning", "country": "China", "avatarUrl": "https://wx.qlogo.cn/mmopen/vi_32/Q0j4TwGTfTIqjzlA7EFocFjPrkdM7IAoqcNTIPLIS1mvVxG0BXCMWL483Hx1OoCuoA4ia9nXY7ye24esvhsF05g/132" }
    wx.setStorageSync('userinfo', myinfo);


    var user = wx.getStorageSync('user');
    if (!user) {
      that.setData({
        shouquan: 1
      })
    } else {
      that.setData({
        shouquan: 0
      })
      http.req('/Wxpro/pro_info' , { id: options.id, uid: user.userid}, function (prores) {
       
       
        that.setData({
          info: prores,
          spec: prores.pro_gg
        })

       
       
        if (prores.shoucang == '取消收藏') {
          that.setData({
            collect: true,
          })
        }

        WxParse.wxParse('content', 'html', prores.content, that, 5);
        WxParse.wxParse('canshu', 'html', prores.canshu, that, 5);

        that.init_attr(prores.pro_gg);

      });
      //会员等级
      // http.req("/Wxapi/userlvl", { uid: user.userid }, function (res) {
      //   that.setData({
      //     hylvl: res
      //   })
      // });


    }

  },
  onShow: function () {
    var cart = wx.getStorageSync('cart')
    if (cart) {
      this.setData({
        carts: cart
      });
    } else {
      this.setData({
        carts: []
      });
    }
    this.cartcount();
    
  },

  // 滑动切换tab
  bindChange: function (e) {
    var that = this;
    that.setData({ currentTab: e.detail.current });
  },
  // 点击tab切换
  swichNav: function (e) {
    var that = this;
    console.log("点击的滑动门" + e.target.dataset.current)
    if (this.data.currentTab === e.target.dataset.current) {
      return false;
    } else {
      that.setData({
        currentTab: e.target.dataset.current
      })
    }
  },

  //选择规格
  selectClick: function (event) {
    console.log(event)
    var that = this;
    var thatprofile = event.target.dataset.profile;
    // this.data.model[event.currentTarget.id].selectImage

    for (var i = 0; i < that.data.modelaa.length; i++) {

      if (event.currentTarget.id == i) {
        that.data.modelaa[i].change = true
      }
      else {
        that.data.modelaa[i].change = false
      }
    }
    that.setData(that.data);
    that.setData({
      defaultguige: thatprofile
    });
  },
  bindMinus: function () {
    var that = this;
    var buynum = that.data.buynum;
    // 如果大于1时，才可以减
    if (buynum > 1) {
      buynum--;
    }
    // 只有大于一件的时候，才能normal状态，否则disable状态
    var minusStatus = buynum <= 1 ? 'disabled' : 'normal';
    // 将数值与状态写回
    that.setData({
      buynum: buynum,
      minusStatus: minusStatus
    });
  },
  /* 点击加号 */
  bindPlus: function () {
    var that = this;
    var buynum = that.data.buynum;
    // 不作过多考虑自增1
    buynum++;
    if (buynum > that.data.info.num) {
      wx.showModal({
        title: '温馨提示',
        showCancel: false,
        content: '数量不能大于当前库存',
      })
      that.setData({
        buynum: that.data.info.num
      })
      return false
    }
    // 只有大于一件的时候，才能normal状态，否则disable状态
    var minusStatus = buynum < 1 ? 'disabled' : 'normal';
    // 将数值与状态写回
    that.setData({
      buynum: buynum,
      minusStatus: minusStatus
    });
  },
  /* 输入框事件 */
  bindManual: function (e) {
    var that = this;
    var buynuma = e.detail.value;
    // 将数值与状态写回
    if (buynuma == '') {
      that.data.buynum = '1'
      that.setData({
        buynum: that.data.buynum
      });
    } else if (buynuma == 0) {
      that.data.buynum = '1'
      that.setData({
        buynum: that.data.buynum
      });
    } else {
      that.setData({
        buynum: that.data.buynum
      });
    }
  },
  //展开隐藏 规格选择
  onChangeShowState: function () {
    var that = this;
    that.setData({
      showView: (!that.data.showView)
    })
  },
  collectchange: function () {
    var that = this, collecttig = that.data.collect
    if (collecttig == false) {
      that.setData({
        collect: true
      })
      wx.showToast({
        title: '收藏成功',
        icon: 'success',
        duration: 2000
      })
    } else {
      that.setData({
        collect: false
      })
      wx.showToast({
        title: '取消收藏',
        icon: 'success',
        duration: 2000
      })
    }
  },
  //收藏
  shoucang: function (e) {

    var that = this;
    var user = wx.getStorageSync('user');
    let scact = e.currentTarget.dataset.scact;

    http.req('/Wxpro/shoucang', { pid: that.data.info.id, uid: user.userid, act: scact}, function (prores) {
    });
    http.req('/Wxpro/pro_info' , { id: that.data.info.id, uid: user.userid}, function (prores) {
      that.setData({
        info: prores,
        spec: prores.pro_gg
      })
      WxParse.wxParse('content', 'html', prores.content, that, 5);
      WxParse.wxParse('canshu', 'html', prores.canshu, that, 5);

      that.init_attr(prores.pro_gg);

    });



    if (that.data.info.shoucang == '收藏') {
      var sctitle = '收藏成功';
      that.setData({
        collect: true,
        sc_title: "已收藏"
      })
    } else if (that.data.info.shoucang == '取消收藏') {
      var sctitle = '取消收藏'
      that.setData({
        collect: false,
        sc_title: "收藏"
      })
    }
    wx.showToast({
      title: sctitle,
      icon: 'success',
      duration: 1000
    })

  },
  //立即购买
  lijigoumai: function () {
    var that = this
    wx.navigateTo({
      url: '/pages/shop/order/tjorder/tjorder'
    })
  },
  //去商城
  gotoshop: function () {
    var that = this
    tips.godaohang('/pages/shop/index/index')
  },
  //跳转到购物车页
  gotoshopcart() {
    tips.goto('/pages/shop/shoppingcart/shoppingcart')
  },
  //分享
  onShareAppMessage: function () {
    var that = this
    return {
      title: '浙江网盛生意宝股份有限公司 - Cloud Ai',
      path: '',
      imageUrl: "",
      success: (res) => {
        console.log("转发成功", res);
      },
    }
  },
  //去会员中心
  gotomain: function () {
    var that = this
    tips.goto('/pages/shop/main/index/index')
  },
  bindGetUserInfo: function (e) {
    var that = this
    shouquan.login(e, that, function () {
      that.setData({
        shouquan: 0
      })
      http.req('/Wxpro/pro_info/id/' + that.data.getid + '/uid/' + wx.getStorageSync('user').userid, {}, function (prores) {
       
        that.setData({
          info: prores,
          spec: prores.pro_gg
        })

      
      
        if (prores.shoucang == '取消收藏') {
          that.setData({
            collect: true,
          })
        }

        WxParse.wxParse('content', 'html', prores.content, that, 5);
        WxParse.wxParse('canshu', 'html', prores.canshu, that, 5);

        that.init_attr(prores.pro_gg);

      });
      //会员等级
      // http.req("/Wxapi/userlvl", { uid: wx.getStorageSync('user').userid }, function (res) {
      //   that.setData({
      //     hylvl: res
      //   })
      // });
      // that.countDown_cuo('86391');

    })
  },
  init_attr: function (arr) {
    //初始化规格选择
    var that = this
    var selectIndexArray = [];
    var name = "";
    var post_name = "";
    var spec = arr;

    var size = spec.length;
    for (var i = 0; i < size; i++) {
      selectIndexArray.push({ key: i, value: spec[i].child[0].name });
      name += ' "' + selectIndexArray[i].value + '" ';
      spec[i].child[0].isSelect = true
      post_name += selectIndexArray[i].value + ","
    }
    var data = {
      pro_ggval: post_name,
      pid: that.data.info.id,
      pro_gg_count: that.data.info.pro_gg_count

    }

    // return
    http.req('/Wxpro/pro_gg_select', data, function (res) {
      console.log('规格',res)
      that.setData({
        pro_gg_info: res
      })

    });
    this.setData({
      spec: spec,
      selectIndexArray: selectIndexArray,
      selectName: name
    });
    console.log(name);
  },
  clickAttr: function (e) {
    // console.log(e);return;
    var that = this
    var selectIndex = e.currentTarget.dataset.selectIndex;
    var attrIndex = e.currentTarget.dataset.attrIndex;
    var spec = this.data.spec;
    var count = spec[selectIndex].child.length;
    // console.log(count); return;
    for (var i = 0; i < count; i++) {
      spec[selectIndex].child[i].isSelect = false;
    }
    spec[selectIndex].child[attrIndex].isSelect = true;
    var name = spec[selectIndex].child[attrIndex].name;//点击属性的名称\
    //点击过，修改属性
    var selectName = "";
    var post_name = "";
    //点击过，修改属性
    var selectIndexArray = this.data.selectIndexArray;
    selectIndexArray[selectIndex].value = name;
    var selectIndexArraySize = selectIndexArray.length;
    //将数组的所有属性名拼接起来
    for (var i = 0; i < selectIndexArraySize; i++) {
      selectName += ' "' + selectIndexArray[i].value + '" ';
      post_name += selectIndexArray[i].value + ',';
    }

    var data = {
      pro_ggval: post_name,
      pid: that.data.info.id,
      pro_gg_count: that.data.info.pro_gg_count

    }

    // return
    http.req('/Wxpro/pro_gg_select', data, function (res) {

      that.setData({
        pro_gg_info: res
      })

    });
    this.setData({
      spec: spec,//变换选择框
      selectName: selectName,
    });
  },
  lj_cart: function () {
    var that = this
    var info = that.data.info;
    var gginfo = that.data.pro_gg_info;
    if (gginfo.num == '0') {
      wx.showModal({
        title: '温馨提示',
        showCancel: false,
        content: '暂无库存'
      })
      return false
    }
    
    var carts = [];
    var proinfo = {
      pro_id: info.id,
      pro_name: info.title,
      pro_pic: info.pro_list_pic,
      gg_price: gginfo.price,
      gg_num: that.data.buynum,
      gg_id: gginfo.id,
      gg_name: that.data.selectName,
      maxcount: gginfo.num,
      gg_ghprice: gginfo.ghprice,
      gg_yjprice: gginfo.yjprice,
      beizhu: "",
      select: "success",
      bind: "dianji_ico_circle",
      is_mj: info.is_mj,
      is_yhq: info.is_yhq
    }
    var carts_arr = {
      pro: [proinfo]
    }
    carts.push(carts_arr)
    var price = that.data.buynum * gginfo.price


    wx.setStorageSync('lj_cart', carts);
    wx.setStorageSync('ljcart_count', that.data.buynum);
    wx.setStorageSync('ljcart_price', price.toFixed(2));

    wx.navigateTo({
      url: '/pages/shop/order/tjorder/tjorder?lj=1'
    })
  },
  addcart: function () {
    var that = this;
    var info = that.data.info;
    var gginfo = that.data.pro_gg_info;
    if (gginfo.num == '0') {
      wx.showModal({
        title: '温馨提示',
        showCancel: false,
        content: '暂无库存'
      })
      return false
    }


    var cart = wx.getStorageSync('cart')

    


    if (cart) {
      var carts = cart;
    } else {
      var carts = [];
    }

    var proinfo = {
      pro_id: info.id,
      pro_name: info.title,
      pro_pic: info.pro_list_pic,
      gg_price: gginfo.price,
      gg_num: that.data.buynum,
      gg_id: gginfo.id,
      gg_name: that.data.selectName,
      maxcount: gginfo.num,
      gg_ghprice: gginfo.ghprice,
      gg_yjprice: gginfo.yjprice,
      beizhu: "",
      select: "success",
      bind: "dianji_ico_circle",
      is_mj: info.is_mj,
      is_yhq: info.is_yhq
    }
    var carts_arr = {
      pro: [proinfo]
    }
    var len = carts.length;
    console.log(len)
    if (len) {
      var d = '1';
      for (var i = 0; i < carts.length; i++) {

        var s = '1';
        var d = '2';
        console.log("相同店铺")
        for (var j = 0; j < carts[i].pro.length; j++) {
          console.log("循环店铺下的商品")
          console.log(carts[i].pro[j].pro_id)
          console.log(info.id)
          console.log(carts[i].pro[j].gg_id)
          console.log(gginfo.id)
          if (carts[i].pro[j].pro_id == info.id && carts[i].pro[j].gg_id == gginfo.id) {
            console.log(1)
            var add_num = carts[i].pro[j].gg_num + that.data.buynum;

            if (add_num > gginfo.num) {
              console.log("购买数量大于当前库存")
              wx.showModal({
                title: '温馨提示',
                showCancel: false,
                content: '数量不能大于当前库存'
              })
              return false
            } else {
              console.log("增加已存在购物车中商品的数量")
              carts[i].pro[j].gg_num = add_num;
              var s = '2';
              break
            }
          }
        }
        if (s == '1') {
          console.log("在店铺下增加新产品")
          carts[i].pro.push(proinfo)
        }

      }
      if (d == '1') {
        console.log("在购物车中增加一个新的店铺")
        carts.push(carts_arr)
      }

    } else {

      carts.push(carts_arr)
    }
    wx.showToast({
      title: '添加成功',
      icon: 'success',
      duration: 1000
    })

    wx.setStorageSync('cart', carts);
    
    this.cartcount();

  },
  cartcount: function () {
    var num = 0
    var total_price = 0
    var that = this;
    var cart = wx.getStorageSync('cart')
    var len = cart.length;
    if (len) {
      for (var i = 0; i < len; i++) {
        for (var j = 0; j < cart[i].pro.length; j++) {

          total_price += parseInt(cart[i].pro[j].gg_num) * Number(cart[i].pro[j].gg_price)
          num += parseInt(cart[i].pro[j].gg_num);
        }
      }
    }
    console.log(num)
    wx.setStorageSync('cart_count', num);
    wx.setStorageSync('cart_price', total_price.toFixed(2));
    that.setData({
      cart_count: num
    })

  }


})




